package com.yuye.cloud.common.utils.ip;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;
/**
 * 获取 Ip相关的方法
 * @author xgf
 *
 */
public class IpUtils {
	
	/**
	 * ip 正则匹配
	 * @param ip Ip
	 * @return 经过处理之后的 IP
	 */
	public static String ipMatch(String ip){
	    if (Pattern.matches("[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(/.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+/.?", ip)) {
	        return ip;
	    }
	    return "0";
	}
	
	/**
	 * 获取当前 request的ip
	 * @param request  请求
	 * @return 正确的客户端 ip
	 */
	public  static  String  getIpAddress(HttpServletRequest  request)  {
	    String  ip  =  request.getHeader("x-forwarded-for");
	    if (ip  ==  null  ||  ip.length()  ==  0  ||  "unknown".equalsIgnoreCase(ip))  {
	        ip  =  request.getHeader("Proxy-Client-IP");
	    }
	    if (ip  ==  null  ||  ip.length()  ==  0  ||  "unknown".equalsIgnoreCase(ip))  {
	        ip  =  request.getHeader("WL-Proxy-Client-IP");
	    }
	    if (ip  ==  null  ||  ip.length()  ==  0  ||  "unknown".equalsIgnoreCase(ip))  {
	        ip  =  request.getRemoteAddr();
	    }
	    if (ip.contains(","))  {
	        return  ip.split(",")[0];
	    }
	    else  {
	        return  ip;
	    }
	}

}
